<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header :to="'/activeFault'" :back="true" />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <Left />
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <!-- 标题 -->
        <headline :name="`${provinceName}活动断层分布图`" />
        <!-- 地图 -->
        <div class="app-map">
          <SystemSelect :styles="{ position: 'absolute', top: '0px', left: '42px' }" />
          <OlMap
            :blueChina="false"
            :refId="'disasterLossessecond'"
            style="height: 100%"
            @getMap="getMap"
            @mapClick="mapClick"
          ></OlMap>
          <MutilLegend
            style="position: absolute; left: 42px; bottom: 150px"
            :titles="legendTitles"
            :items="legendItems"
            :items-per-column="4"
          ></MutilLegend>
          <div ref="popupElement" class="popup-bg" id="map-popup">
            <div class="triangle"></div>
            <div class="popup-head">
              <div class="popup-head-title">{{ popData.name }}</div>
            </div>
            <div class="popup-content">
              <div class="popup-content-item" v-for="(item, index) in popData.list" :key="index">
                <div>{{ item.key }}：</div>
                <div>{{ item.value }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <Right @changeType="changeType"></Right>
      </div>
    </div>
  </div>
</template>
<script setup>
import MutilLegend from '@/components/MutilLegend';
import Left from './left/index.vue';
import Right from './right/index.vue';
import OlMap from '@/components/Olmap';
import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import { getTileLayerByName, getProviceFeature } from '@/utils/matchProvince';
import useArcMapDataStore from '@/store/modules/arcMap';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import { getBaseDir } from '@/map/projMap.js';
import { Style, Circle as CircleStyle, Fill, Stroke, Text } from 'ol/style';
import { Feature } from 'ol';
import Overlay from 'ol/Overlay';
import { Util } from '@supermap/iclient-ol';
import { ArcgisService } from '@/map/ArcgisService';

const { getAllArcMapData } = useArcMapDataStore();
const changeTypeData = ref(['晚更新世断层', '早中更新世断层', '前第四纪断层', '全新世断层']);

const route = useRoute();
const { provinceName, num } = route.query;
const mapInstance = ref(null);
const proviceFeature = ref(null);
const popupElement = ref();
const mapPopupLayer = ref(null);
const popData = reactive({
  name: '',
  list: [
    {
      key: '断层名称',
      value: '',
    },
    {
      key: '活动时代',
      value: '',
    },
    {
      key: '断层性质',
      value: '',
    },
    {
      key: '断层走向',
      value: '0',
    },
    {
      key: '断层倾向',
      value: '0',
    },
    {
      key: '断层长度',
      value: '0',
    },
  ],
});
const legendTitles = [
  { title: '图例', subTitle: '' },
  { title: '断层数量（条）', subTitle: '' },
];
const legendItems = [
  { label: '全新世', color: 'rgba(255,37,37,1)', w: 15, h: 4, r: 10 },
  { label: '晚更新世', color: 'rgba(227,46,255,1)', w: 15, h: 4, r: 10 },
  { label: '早中更新世', color: 'rgba(37,255,130,1)', w: 15, h: 4, r: 10 },
  { label: '前第四纪', color: 'rgba(253,190,65,1)', w: 15, h: 4, r: 10 },
  { label: '>300', color: 'rgba(26,66,194,1)', w: 15, h: 8, r: 0 },
  { label: '150-300', color: 'rgba(48, 96, 255, 1)', w: 15, h: 8, r: 0 },
  { label: '50-150', color: 'rgba(95, 133, 255, 1)', w: 15, h: 8, r: 0 },
  { label: '0-50', color: 'rgba(146, 160, 240, 1)', w: 15, h: 8, r: 0 },
];
const changeType = (data) => {
  changeTypeData.value = data;
  let mapLyaers = mapInstance.value.getLayers();
  console.log('mapLyaers--', mapLyaers);
  mapLyaers.forEach((layer) => {
    console.log('layer---', layer);
    if (layer.get('arcName')) {
      if (changeTypeData.value.includes(layer.get('arcName'))) {
        layer.setVisible(true);
      } else {
        layer.setVisible(false);
      }
    }
  });
};
const getMap = (map) => {
  mapInstance.value = map.value;
  getProviceLayer();
  createOverlayLayer();
};
let selectedFeature = null;
const mapClick = async (event) => {
  console.log('event', event);
  if (selectedFeature) {
    // 恢复先前选中要素的样式
    restoreOriginalStyle(selectedFeature);
    selectedFeature = null;
    mapPopupLayer.value.setPosition(undefined);
  }

  const features = mapInstance.value.getFeaturesAtPixel(event.pixel);
  console.log('features--', features);
  if (features.length > 0) {
    // start
    selectedFeature = features.find((feature) => feature.get('FID'));
    if (selectedFeature) {
      let arcgisService = new ArcgisService({});
      let attributes = await arcgisService.getFeatureDataByFid(selectedFeature.get('FID'));
      popData.name = attributes['断层名称'];
      for (let i = 0; i < popData.list.length; i++) {
        const item = popData.list[i];
        item['value'] = attributes[item['key']];
      }

      const newStyle = createNewStyle(selectedFeature);
      selectedFeature.setStyle(newStyle);

      // 获取要素的坐标信息
      popupElement.value.style.display = 'block';
      let coordinate = mapInstance.value.getEventCoordinate(event.originalEvent);
      // 设置弹出框的位置
      mapPopupLayer.value.setPosition(coordinate);
    }
  } else {
    selectedFeature = null;
    mapPopupLayer.value.setPosition(undefined);
  }
};
// 恢复原始样式
const restoreOriginalStyle = (feature) => {
  const originalStyle = createOriginalStyle(feature); // 用于创建原始样式的函数
  feature.setStyle(originalStyle);
};
const createOriginalStyle = (feature) => {
  return new Style({
    stroke: new Stroke({
      color: feature.getStyle().getStroke().getColor(),
      width: 2,
    }),
  });
};
const createNewStyle = (feature) => {
  return new Style({
    stroke: new Stroke({
      color: feature.getStyle().getStroke().getColor(),
      width: 5,
    }),
  });
};
const createOverlayLayer = () => {
  let popup = document.getElementById('map-popup');
  mapPopupLayer.value = new Overlay({
    element: popup,
    positioning: 'center-left',
  });
  mapInstance.value.addOverlay(mapPopupLayer.value);
};
const addArcLayer = async () => {
  if (!proviceFeature.value) {
    proviceFeature.value = await getProviceFeature(provinceName);
  }
  let data = getAllArcMapData;
  if (!data || Array.from(data.keys()).length !== 4) {
    let prom = useArcMapDataStore().getAllArcData();
    prom.then((res) => {
      for (let i = 0; i < changeTypeData.value.length; i++) {
        const name = changeTypeData.value[i];
        let layer = res.get(name);
        mapInstance.value.addLayer(layer);
        Util.setMask(layer, proviceFeature.value);
      }
    });
  } else {
    for (let i = 0; i < changeTypeData.value.length; i++) {
      const name = changeTypeData.value[i];
      let layer = data?.get(name);
      if (layer) {
        layer.setVisible(true);
        mapInstance.value.addLayer(layer);
        Util.setMask(layer, proviceFeature.value);
      }
    }
  }
};
const getProviceLayer = async () => {
  proviceFeature.value = await getProviceFeature(provinceName);
  mapInstance.value.getView().setCenter(proviceFeature.value.get('center'));
  let layer = await getTileLayerByName(provinceName);
  layer.setZIndex(0);
  mapInstance.value.addLayer(layer);
  fitToExtent();
  addArcLayer();
  setFaultNumLayer();
};
const setFaultNumLayer = () => {
  var color = {
    0: 'rgba(146, 160, 240, 0.5)',
    1: 'rgba(95, 133, 255, 0.5)',
    2: 'rgba(48, 96, 255, 0.5)',
    3: 'rgba(26, 66, 194, 0.5)',
  };
  let layer = new VectorLayer({
    source: new VectorSource(),
    setZIndex: 0,
  });
  mapInstance.value.addLayer(layer);
  proviceFeature.value.setStyle(
    new Style({
      fill: new Fill({ color: color[num] }),
      text: new Text({
        font: '10px Calibri,sans-serif',
        fill: new Fill({ color: '#fff' }),
      }),
    })
  );
  layer.getSource().addFeature(proviceFeature.value);
};
const fitToExtent = () => {
  const provinceGeometry = proviceFeature.value.getGeometry();
  // 计算放大后的视图范围
  const provinceExtent = provinceGeometry.getExtent();
  // 更新地图视图以显示具体的省份地图
  mapInstance.value.getView().fit(provinceExtent, { padding: [20, 20, 150, 20] });
};
</script>
<style scoped lang="scss">
.app-main {
  display: flex;
  justify-content: space-between;

  :deep(.app-left) {
    margin-left: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;
    position: relative;

    .app-left-item {
      flex: auto;
    }
  }

  .app-map {
    width: 960px;
    height: 100%;
    //overflow: hidden; //test
    position: relative;
  }

  :deep(.app-right) {
    margin-right: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;

    .app-right-item {
      flex: auto;
    }
  }

  :deep(.app-left-item) .subheadings + div,
  :deep(.app-right-item) .subheadings + div {
    top: 0 !important;
  }

  :deep(.subheadings) {
    margin-bottom: -35px;
  }
}

/* start */
.popup-bg {
  /* left: 20px; */
  width: 400px;
  height: 275px;
  /* background: linear-gradient(NaNdeg, rgba(5, 12, 53, 0.8) 0%, rgba(4, 16, 89, 0.8) 55%, rgba(6, 40, 150, 0.8) 100%); */
  background: rgba(6, 40, 150, 0.8);
  border-radius: 8px 8px 8px 8px;
  opacity: 1;
  border: 2px solid #0190f9;
  display: flex;
  padding: 17px 15px;
  flex-direction: column;
  position: relative;
  .triangle {
    position: absolute;
    top: 50%;
    left: -10px;
    transform: translateY(-50%);
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #0190f9;
  }
  .popup-head {
    justify-content: center;

    display: flex;
    flex-direction: row;
    font-size: 18px;
    font-family: Source Han Sans CN-Bold, Source Han Sans CN;
    font-weight: bold;
    color: #ffffff;
    line-height: 23px;
    .popup-head-title {
      color: #46ffff;
    }
    .popup-head-x {
      margin-left: auto;
      width: 12px;
      height: 12px;
      color: #e6f4fd;
      opacity: 1;
    }
  }
  .popup-content {
    height: 100%;
    margin-top: 16px;
    display: flex;
    flex-direction: column;
    font-size: 16px;
    font-family: Source Han Sans CN-Medium, Source Han Sans CN;
    font-weight: 500;
    color: #e6f4fd;
    line-height: 23px;
    .popup-content-item {
      display: flex;
      flex-direction: row;
      margin-top: 10px;
    }
  }
}
:deep(.ol-overlaycontainer-stopevent) {
  z-index: 2;
}
/* end */
</style>
